use std::{fs::File, io::Read,io::BufReader,io::BufRead};

#[derive(Default)]
#[derive(serde::Serialize,serde::Deserialize)]
pub struct WordCard{
    pub title:String,
    pub meaning:String,
    del:bool,
    progress:f32,
    delable:bool,
    #[serde(skip)]
    dactive:bool,
}

impl WordCard{
    pub fn new(title:String,meaning:String)->Self{
        WordCard { title: title, meaning: meaning,..Default::default() }
    }
    pub fn ui(&mut self,ui:&mut eframe::egui::Ui,index:usize){
        ui.horizontal(|ui|{

            ui.add_sized([111.,3.], eframe::egui::Label::new(&self.title)).on_hover_text(&self.meaning);
            if !self.dactive{
                if ui.button("+1").clicked(){
                    self.progress+=0.1;
                    if self.progress>=1.0{
                        self.delable = true;
                    }
                    self.dactive=true;
                };
            }
            
            ui.label(index.to_string());
        
        });
        ui.horizontal(|ui|{
            ui.add(eframe::egui::ProgressBar::new(self.progress).desired_width(111.));
            if !self.dactive{
                if ui.button("clr").clicked(){
                    self.progress = 0.;
                    self.dactive = true;
                    self.delable = false;
                };
                
                ui.add_enabled_ui(self.delable, |ui|{
                    if ui.button("del").clicked(){
                        self.del = true;
                        self.dactive = true;
                    }
                });
            }
            
        });
        ui.separator();
    }
    pub fn isdel(&self)->bool{
        self.del
    }
}
#[derive(Default)]
#[derive(serde::Deserialize,serde::Serialize)]
pub struct PageFrame{
    pub wordcards:Vec<WordCard>,
    pub pages:usize,
    pub page_idx:usize,
    pub width_num:usize,
    pub wordcount:usize,
    #[serde(skip)]
    todel:i32,
}
impl PageFrame {
    pub fn new()->Self{
        Self { width_num:3,wordcount:30,todel:-1, ..Default::default() }
    }
    pub fn load()->Self{
        let mut frames = Self::new();
        // let mut wordcards =Vec::new();
        // #[cfg(not(target_arch = "wasm32"))]
        if let Ok(mut file) = std::fs::File::open("db.json"){
            let mut ddata = String::new();
            if let Ok(_) = file.read_to_string(&mut ddata){
                if let Ok(s) = serde_json::from_str(&ddata){
                    frames = s;
                }
            }
        }
        frames.todel = -1;
        frames
        // Self { wordcards: wo, pages: (), page_idx: (), width_num: (), wordcount: (), todel: () }
        // #[cfg(target_arch = "wasm32")]
        // let mut sd = String::new();
        // let cc = Arc::new(Mutex::new(sd));
        // let cc1 =cc.clone();
        // if let Ok(_) = ws::connect("ws://127.0.0.1:9876",|out|{
        //     out.send("r").unwrap();
        //     move |msg|{
        //         if let ws::Message::Text(ssd) = msg{
        //             // sd.push_str(&ssd);
        //             if let Ok(mut ccd) = cc1.lock(){
        //                 ccd.push_str(&ssd);
        //             }
                    
        //         }
        //         out.close(ws::CloseCode::Normal)
        //     }
        // }){
        //     if let Ok(s) = serde_json::from_str(&sd){
        //         wordcards = s;
        //     }
        // }
        // if let Ok((mut serder,receiver)) = ewebsock::connect("ws://127.0.0.1:9876"){
        //     serder.send(ewebsock::WsMessage::Text("r".into()));
        //     while let Some(cdata) = receiver.try_recv(){
        //         if let ewebsock::WsEvent::Message(ewebsock::WsMessage::Text(sd))=cdata{
        //             println!("{}",sd);
        //             if let Ok(s) = serde_json::from_str(&sd){
        //                 wordcards = s;
        //             }
        //         }
        //     }
        // };
        
        // for idx in 0..10000{
        //     wordcards.push(WordCard::new(format!("t{}",idx), format!("m0oooooooooooooooooooooooooooooooooooooooooooooooooo{}",idx)));
        // }
    }

    pub fn add_word(&mut self,filepath:&String){
        let mut tempbuf = String::new();

        if let Ok(mut d_file) = File::open(filepath){
            // d_file.lines()
            for idx in BufReader::new(d_file).lines(){
                if let Ok(words) = idx{
                    if let Some((title,meaning))=words.split_once(" "){
                        self.wordcards.push(WordCard::new(title.to_string(), meaning.to_string()));
                    }
                    // let vc:Vec<&str> = words.split(" ").collect();
                }
            }
            // d_file.read_to_string(&mut tempbuf).unwrap();
            
            println!("{}",tempbuf);
        }
    }
    fn is_repeat(&self,wordname:&String)->bool{
        for idx in &self.wordcards{
            if wordname == &idx.title{
                return false;
            }
        }
        true
    }

    pub fn ui(&mut self,ui:&mut eframe::egui::Ui){
        eframe::egui::ScrollArea::horizontal().show(ui, |ui|{
                egui_extras::TableBuilder::new(ui)
                .resizable(true)
                .max_scroll_height(999.)
                .auto_shrink([false;2])
                .cell_layout(eframe::egui::Layout::top_down(eframe::egui::emath::Align::LEFT).with_cross_justify(true))
                .columns(egui_extras::Column::auto().at_most(233.), self.width_num).body(|mut body|{
                    for idx in 0..self.wordcount/self.width_num+1{
                        body.row(50., |mut ui|{
                            for idy in 0..self.width_num{
                                let vecidx = idx*self.width_num+idy+self.page_idx*self.wordcount;
                                if let Some(wd)=self.wordcards.get_mut(vecidx){
                                    ui.col(|ui|{
                                        wd.ui(ui,idx*self.width_num+idy);
                                        if wd.isdel(){
                                            self.todel = vecidx as i32;
                                        }
                                    });
                                }
                            }
                        });
                    }
                    
                    // for idx in 0..self.wordcards.len()/self.width_num+1{
                    //     // ui.horizontal(|ui|{
                    //         body.row(50., |mut ui|{
                    //             for idy in 0..self.width_num{
                    //                 let iidx = idx*self.width_num+idy;
                    //                 if let Some(wd)=self.wordcards.get_mut(iidx){
                    //                     ui.col(|ui|{
                    //                         wd.ui(ui,idx*self.width_num+idy);
                    //                         if wd.isdel(){
                    //                             self.todel = iidx as i32;
                    //                         }
                    //                     });
                    //                 }
                    //             }
                    //         });
                            
                    //     // });
                        
                    // }
                    
                });
            // });
            if self.todel>-1 && self.todel<self.wordcards.len() as i32{
                self.wordcards.remove(self.todel as usize);
                self.todel = -1;
            }
        });
        

        // for idx in 0..self.wordcards.len()/self.width_num{
        //     ui.horizontal(|ui|{
        //         for idy in 0..self.width_num{
        //             if let Some(wd)=self.wordcards.get_mut(idx*self.width_num+idy){
        //                 wd.ui(ui);
        //             }
        //         }
        //     });
            
        // }
        
    }

}
#[derive(Default)]
pub struct WordAdd{
    addtxt:String,
    prasewd:Vec<(String,String)>,
    waitadd:bool,
    addway:usize,
}


impl WordAdd {
    pub fn new()->Self{
        Self { ..Default::default() }
    }
    fn ui_top(&mut self,ctx:&eframe::egui::Context){
        eframe::egui::TopBottomPanel::top("wat").show(ctx, |ui|{
            ui.horizontal(|ui|{

                if ui.radio_value(&mut self.addway, 0, "abandon 放弃").clicked(){
                    self.prasewd.clear();
                    self.prasetovec();
                };
                if ui.radio_value(&mut self.addway, 1, "有道导出XML").clicked(){
                    self.prasewd.clear();
                    self.xmltovec();
                };
                ui.radio_value(&mut self.addway, 2, "Json");
            });
        });
    }
    fn ui_central(&mut self,ctx:&eframe::egui::Context){
        eframe::egui::CentralPanel::default().show(ctx, |ui|{
            eframe::egui::ScrollArea::vertical().show(ui, |ui|{
                ui.add(eframe::egui::TextEdit::multiline(&mut self.addtxt).desired_width(f32::INFINITY).desired_rows(20).frame(false));
         
                if ui.input_mut(|i| i.consume_key(eframe::egui::Modifiers::CTRL, eframe::egui::Key::V)){
                    self.prasewd.clear();
                    if !self.addtxt.is_empty(){
                        match self.addway {
                            0 =>{self.prasetovec()},
                            1 =>{self.xmltovec()},
                            3 =>{},
                            _ =>{},
                        }
                        // self.prasetovec();
                    }
                };
            });
            
            // if ui.input(|i| i.consume_key(eframe::egui::Modifiers::CTRL, eframe::egui::Key::V)) {
            //     println!("pre a");
            // };
        });
    }
    fn ui_right(&mut self,ctx:&eframe::egui::Context){
        eframe::egui::SidePanel::right("war").show(ctx, |ui|{
            eframe::egui::ScrollArea::vertical().show(ui, |ui|{
                for (title,mean) in &self.prasewd{
                    ui.horizontal(|ui|{
                        ui.label(title);
                        ui.separator();
                        ui.label(mean);
                    });
                    ui.separator();
                }
            });
        });
    }
    fn ui_bottom(&mut self,ctx:&eframe::egui::Context,openwindow:&mut bool,tovec:&mut PageFrame){
        eframe::egui::TopBottomPanel::bottom("wab").show(ctx, |ui|{
            ui.horizontal(|ui|{
                if ui.button("确定").clicked(){
                    if self.prasewd.len()>0{
                        for (idx,idy) in self.prasewd.clone(){
                            tovec.wordcards.push(WordCard::new(idx, idy));
                        }
                        self.prasewd.clear();
                        self.waitadd = true;
                        *openwindow = false;
                    }
                    
                };
                if ui.button("取消").clicked(){
                    *openwindow = false;
                };
            });
        });
    }
    pub fn ui(&mut self,ctx:&eframe::egui::Context,openwindow:&mut bool,tovec:&mut PageFrame){
        self.ui_top(ctx);
        self.ui_bottom(ctx,openwindow,tovec);
        self.ui_right(ctx);
        self.ui_central(ctx);
    }
    fn prasetovec(&mut self){
        for idx in self.addtxt.lines(){
            if let Some((title,mean)) = idx.split_once(" "){
                self.prasewd.push((title.to_string(),mean.to_string()));
            }
        }
    }
    fn xmltovec(&mut self){
        use xmltree::Element;
        if let Ok(names_element) = Element::parse(self.addtxt.as_bytes()){
            for idx in &names_element.children{
                let mut s_word = String::new();
                let mut s_trans= String::new();
                if let Some(cc) = idx.as_element(){
                    if let Some(word) = cc.get_child("word"){
                        if let Some(value) = word.get_text(){
                            s_word.push_str(&value);
                        }
                    };
                    if let Some(word) = cc.get_child("trans"){
                        if let Some(value) = word.get_text(){
                            s_trans.push_str(&value);
                        }
                    };
                    
                };
                if !(s_word.is_empty()||s_trans.is_empty()){
                    self.prasewd.push((s_word,s_trans));
                }
            }
        }
    }

}